<template>
  <div class="ai-chat-view">
    <!-- 侧边栏 -->
    <div class="sidebar-container" :class="{ collapsed: sidebarCollapsed }">
      <ChatSidebar v-show="!sidebarCollapsed" @toggle-sidebar="toggleSidebar" />

      <!-- 折叠后的迷你侧边栏 -->
      <div v-show="sidebarCollapsed" class="mini-sidebar">
        <el-tooltip content="展开侧边栏" placement="right">
          <el-button
            :icon="Menu"
            @click="toggleSidebar"
            text
            size="large"
            class="expand-btn"
          />
        </el-tooltip>
      </div>
    </div>

    <!-- 主聊天区域 -->
    <div class="chat-main">
      <!-- 顶部标题栏 -->
      <div class="chat-header">
        <div class="header-left">
          <el-button
            v-if="sidebarCollapsed"
            :icon="Menu"
            @click="toggleSidebar"
            text
            size="large"
            class="sidebar-toggle-btn"
          />
          <h2 class="page-title">
            {{ aiChatStore.currentSession?.title || 'AI 助手' }}
          </h2>
        </div>

        <div class="header-right">
          <el-button
            :icon="Plus"
            @click="handleCreateNewSession"
            type="primary"
            size="default"
          >
            新对话
          </el-button>

          <el-button
            :icon="Setting"
            @click="goToSettings"
            size="default"
          >
            设置
          </el-button>

          <el-button
            :icon="Delete"
            @click="handleClearChat"
            :disabled="aiChatStore.messages.length === 0"
            size="default"
          >
            清空对话
          </el-button>
        </div>
      </div>

      <!-- 角色设置栏 -->
      <RoleSelector />

      <!-- 聊天内容区域 -->
      <div class="chat-content">
        <!-- 消息列表 -->
        <div class="chat-messages" ref="messagesContainer">
          <!-- 欢迎消息 -->
          <div v-if="aiChatStore.messages.length === 0" class="welcome-message">
            <div class="welcome-content">
              <el-icon class="welcome-icon"><ChatLineRound /></el-icon>
              <h3>{{ aiChatStore.hasApiKey ? '欢迎使用 AI 助手' : '配置 API Key 开始使用' }}</h3>
              <p v-if="!aiChatStore.hasApiKey" class="welcome-tip">
                请先在设置页面配置 API Key 才能开始与 AI 助手对话
              </p>
              <p v-else class="welcome-tip">
                点击左侧"新对话"按钮开始聊天，或直接在下方输入您的问题
              </p>
            </div>
          </div>

          <!-- 简化版虚拟滚动：只显示最近的消息 -->
          <div v-if="aiChatStore.messages.length > 0" class="virtual-message-list" ref="virtualListRef">
            <ChatMessage
              v-for="message in visibleMessages"
              :key="message.id"
              :message="message"
              :streaming="message.id === aiChatStore.streamingMessageId"
              @retry="handleRetryMessage"
            />

            <!-- 加载指示器 -->
            <div v-if="aiChatStore.isLoading && !aiChatStore.isStreaming" class="loading-indicator">
              <div class="loading-content">
                <el-icon class="loading-icon"><Loading /></el-icon>
                <span>AI 正在思考中...</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input">
          <ChatInputBox
            v-model="inputMessage"
            :disabled="!aiChatStore.hasApiKey || aiChatStore.isLoading"
            :placeholder="aiChatStore.hasApiKey ? '输入您的问题...' : '请先配置 API Key'"
            @send="handleSendMessage"
            @sendImage="handleSendImageGeneration"
            @sendImageUnderstanding="handleSendImageUnderstanding"
            @stop="handleStopMessage"
          />
        </div>
      </div>
    </div>


  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ChatLineRound, Loading, Setting, Delete, Plus, Menu } from '@element-plus/icons-vue'
import { useAIChatStore } from '@/stores/aiChatStore'
import ChatMessage from './components/ChatMessage.vue'
import ChatInputBox from './components/ChatInputBox.vue'
import ChatSidebar from '@/components/ai-chat/ChatSidebar.vue'
import RoleSelector from './components/RoleSelector.vue'
import type { ImageGenerationConfig } from '@/types/aiChat'
// 移除有问题的虚拟滚动库

const router = useRouter()
const aiChatStore = useAIChatStore()

// 响应式数据
const inputMessage = ref('')
const messagesContainer = ref<HTMLElement>()
const virtualListRef = ref()
const sidebarCollapsed = ref(false)

// 简化版虚拟滚动：限制显示的消息数量
const MAX_VISIBLE_MESSAGES = 100 // 最多显示100条消息

const visibleMessages = computed(() => {
  const messages = aiChatStore.messages

  // 如果消息数量超过限制，只显示最新的消息
  if (messages.length > MAX_VISIBLE_MESSAGES) {
    return messages.slice(-MAX_VISIBLE_MESSAGES)
  }

  return messages
})

// 方法
const handleSendMessage = async () => {
  const message = inputMessage.value.trim()
  if (!message || !aiChatStore.hasApiKey || aiChatStore.isLoading || aiChatStore.isStreaming) return

  // 如果没有当前会话，先创建一个（用户发送消息时才创建）
  if (!aiChatStore.currentSession) {
    try {
      await aiChatStore.createNewSession()
    } catch (error) {
      console.error('Create session error:', error)
      ElMessage.error('创建对话失败，请检查后端服务是否启动')
      return
    }
  }

  try {
    inputMessage.value = ''
    await aiChatStore.sendMessage(message)
    scrollToBottom()
  } catch (error) {
    console.error('Send message error:', error)
  }
}

const handleStopMessage = () => {
  aiChatStore.stopStreaming()
}

const handleSendImageGeneration = async (prompt: string, config: ImageGenerationConfig) => {
  if (!prompt.trim() || !aiChatStore.hasApiKey || aiChatStore.isLoading || aiChatStore.isStreaming) return

  // 如果没有当前会话，先创建一个
  if (!aiChatStore.currentSession) {
    try {
      await aiChatStore.createNewSession()
    } catch (error) {
      console.error('Create session error:', error)
      ElMessage.error('创建对话失败，请检查后端服务是否启动')
      return
    }
  }

  try {
    inputMessage.value = ''

    // 构建图片生成请求
    const imageRequest = {
      message: prompt,
      isImageGeneration: true,
      imageSize: config.imageSize,
      batchSize: config.batchSize,
      guidanceScale: config.guidanceScale,
      numInferenceSteps: config.numInferenceSteps,
      image: config.uploadedImage
    }

    // 调用图片生成API（复用现有的sendMessage方法）
    await aiChatStore.sendMessage(prompt, imageRequest)
    scrollToBottom()
  } catch (error) {
    console.error('Image generation error:', error)
    ElMessage.error('图片生成失败')
  }
}

const handleSendImageUnderstanding = async (message: string, imageBase64: string) => {
  if (!message.trim() || !imageBase64 || !aiChatStore.hasApiKey || aiChatStore.isLoading || aiChatStore.isStreaming) return

  // 如果没有当前会话，先创建一个
  if (!aiChatStore.currentSession) {
    try {
      await aiChatStore.createNewSession()
    } catch (error) {
      console.error('Failed to create session:', error)
      ElMessage.error('创建会话失败')
      return
    }
  }

  try {
    // 发送图片理解请求
    await aiChatStore.sendMessage(message, {
      message: message,
      isImageUnderstanding: true,
      uploadedImage: imageBase64
    })

    // 清空输入框
    inputMessage.value = ''

    // 滚动到底部
    scrollToBottom()
  } catch (error) {
    console.error('Image understanding error:', error)
    ElMessage.error('图片理解失败')
  }
}

const handleRetryMessage = async () => {
  try {
    await aiChatStore.retryLastMessage()
    scrollToBottom()
  } catch (error) {
    console.error('Retry message error:', error)
  }
}

const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

const handleCreateNewSession = async () => {
  try {
    await aiChatStore.createNewSession()
  } catch (error) {
    console.error('Create session error:', error)
    ElMessage.error('创建新对话失败')
  }
}

const handleClearChat = async () => {
  try {
    await aiChatStore.clearChat()
  } catch (error) {
    console.error('Clear chat error:', error)
  }
}

const goToSettings = () => {
  router.push('/dashboard/settings')
}

const scrollToBottom = () => {
  nextTick(() => {
    if (virtualListRef.value) {
      // 滚动虚拟列表容器到底部
      virtualListRef.value.scrollTop = virtualListRef.value.scrollHeight
    } else if (messagesContainer.value) {
      // 兜底方案：直接滚动容器
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 监听消息变化，自动滚动到底部
watch(() => aiChatStore.messages.length, () => {
  scrollToBottom()
}, { flush: 'post' })

// 监听流式消息更新
watch(() => aiChatStore.streamingMessageId, () => {
  scrollToBottom()
}, { flush: 'post' })

// 生命周期
onMounted(() => {
  // 初始化时滚动到底部
  scrollToBottom()

  // 新用户没有会话记录是正常的，不需要自动创建
})
</script>

<style lang="scss" scoped>
.ai-chat-view {
  height: 100%;
  display: flex;
  background: var(--el-bg-color);
  overflow: hidden;
}

.sidebar-container {
  width: 230px;
  transition: width 0.3s ease;
  flex-shrink: 0;

  &.collapsed {
    width: 60px;
  }
}

.mini-sidebar {
  width: 60px;
  height: 100%;
  background: var(--el-bg-color-page);
  border-right: 1px solid var(--el-border-color);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px 8px;

  .expand-btn {
    width: 44px;
    height: 44px;
    border-radius: 8px;
  }
}

  // 全局文本换行规则
  * {
    word-wrap: break-word;
    word-break: break-word;
    overflow-wrap: break-word;
    hyphens: auto;
  }

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color);
}

.chat-header {
  padding: 6px 24px;
  border-bottom: 1px solid var(--el-border-color);
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: var(--el-bg-color);
  box-shadow: 0 1px 4px var(--el-box-shadow-light);

  .header-left {
    display: flex;
    align-items: center;
    gap: 12px;

    .sidebar-toggle-btn {
      width: 40px;
      height: 40px;
      border-radius: 6px;
    }

    .page-title {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }

  .header-right {
    display: flex;
    gap: 8px;
    align-items: center;
  }
}

.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  overflow: hidden;
  padding: 0px 15px;
  display: flex;
  flex-direction: column;
  word-wrap: break-word;
  word-break: break-word;
  overflow-wrap: break-word;

  .welcome-message {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;

    .welcome-content {
      text-align: center;
      max-width: 400px;

      .welcome-icon {
        font-size: 48px;
        color: var(--el-color-primary);
        margin-bottom: 16px;
      }

      h3 {
        margin: 0 0 12px 0;
        font-size: 20px;
        color: var(--el-text-color-primary);
      }

      .welcome-tip {
        margin: 0;
        color: var(--el-text-color-regular);
        line-height: 1.6;
      }
    }
  }

  .loading-indicator {
    display: flex;
    justify-content: center;
    padding: 16px;

    .loading-content {
      display: flex;
      align-items: center;
      gap: 8px;
      color: var(--el-text-color-regular);
      font-size: 14px;

      .el-icon {
        font-size: 16px;
      }
    }
  }
}

// 简化版虚拟滚动样式
.virtual-message-list {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.chat-input {
  padding: 11px 24px;
  background: var(--el-bg-color);
}

.api-key-prompt {
  margin: 16px 24px;
}

// 响应式设计
@media (max-width: 768px) {
  .chat-header {
    padding: 16px;
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;

    .header-right {
      align-self: stretch;
      justify-content: flex-end;
    }
  }

  .chat-messages {
    padding: 16px;
  }

  .chat-input {
    padding: 12px 16px;
  }

  .api-key-prompt {
    margin: 12px 16px;
  }
}
</style>
